package cn.hanyx;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import java.io.File;
import java.io.FileInputStream;
import java.nio.file.Paths;
import java.util.Scanner;

/**
 * Created by Administrator on 2017/2/23.
 */
public class IndexUtil {

    /**
     * 创建索引写入器
     * @param indexPath 索引库目录
     * @param create 判断是覆盖索引还是追加索引
     * @return IndexWriter
     * @throws Exception
     */
    public static IndexWriter getIndexWriter(String indexPath, boolean create) throws Exception {
        Directory dir = FSDirectory.open(Paths.get(indexPath)) ;
        Analyzer analyzer = new StandardAnalyzer() ;
        IndexWriterConfig config = new IndexWriterConfig(analyzer) ;
        if (create) { // 追加索引
            config.setOpenMode(IndexWriterConfig.OpenMode.CREATE) ;
        } else { // 覆盖索引
            config.setOpenMode(IndexWriterConfig.OpenMode.CREATE) ;
        }
        IndexWriter indexWriter = new IndexWriter(dir,config) ;
        return indexWriter ;
    }

    public static void createIndex(String sourcePath, String indexPath) throws Exception {
        File indexFile = new File(indexPath) ;
        if (!indexFile.exists()) {
            indexFile.mkdirs() ;
        }
        File[] files = new File(sourcePath).listFiles() ;
        // 创建索引
        Directory fsDir = FSDirectory.open(Paths.get(indexPath));
        IndexWriterConfig indexWriterConfig = new IndexWriterConfig(new StandardAnalyzer());
        IndexWriter indexWriter = new IndexWriter(fsDir, indexWriterConfig);

        for (File file : files) {
            Document document = new Document() ;
            document.add(new Field("fileName", file.getName(), StringField.TYPE_STORED));

            // 读取文件内容
            StringBuilder sb = new StringBuilder(128);
            Scanner scan = new Scanner(new FileInputStream(file)) ;
            while (scan.hasNext()){
                sb.append(scan.next());
            }
            scan.close();
            document.add(new Field("content", sb.toString(), TextField.TYPE_STORED));
            indexWriter.addDocument(document);
        }

        indexWriter.commit();
        indexWriter.close();
    }

    public static void main(String[] args) throws Exception{
        String url =IndexUtil.class.getResource("/").getPath() ;
        String sourcePath = new File(url).getParentFile().getParentFile().getPath() + File.separator + "src/main/resources/";
        String indexPath = "F:\\lucene\\" ;
        IndexUtil.createIndex(sourcePath + "output",indexPath + "index1");
    }
}
